<?php

class Default_IndexController extends Ac_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }
    
    public function indexAction()
    {
        $cache_output = Zend_Registry::get('cache_output');

        //echo '<pre>';        var_dump($this->_request->getParam('module'));exit;
        if ($this->_request->getParam('module') != 'default') {
            throw new Exception('wrong module');
        }
        $this->view->categorydata = Model_Category::getLevel1(array('homepage' => 1, 'status' => Model_Category::STATUS_ACTIVE));

        //description
        $description = $this->view->t('Need a new sofa, television or bed? Something for the kitchen, garden or dining room? Need to find a job or sell your apartment? AsiaClassified.com!');
        if (!empty($description)) {
            $this->view->headMeta()->appendName('og:description', $description);
            $this->view->headMeta()->appendName('description', $description);
        }        
        //default image to the logo
        $this->view->headMeta()->appendName('og:image', $this->view->thumbnail()->scale('/images/logo.png', 130, 110));        
        
        $hp = Model_Todayspick::getHomepage();
        $arr = array();
        foreach($hp as $k => $ls){
			foreach($ls->listing_id as $lsid){
        		if(empty($lsid)){
					continue;
				}
				$arr[] = $lsid;
			}
		}
        
        shuffle($arr);
        $arr = array_slice($arr, 0, 4);
        //$res = Model_Listing::all(array('_id' => array('$in' => $arr)));
        $list = array();
        foreach($arr as $val) {
            $tmp =  Model_Listing::find(new MongoId($val));
            if (!empty($tmp)) {
                $list[] = $tmp;
            }
        }        
        $this->view->todayspick = $list;
        //$this->view->cat_pick = $cat_pick;

        $key_cache = $this->view->key_homepage_intro_user = 'homepage_intro_user'; 
        if (!$cache_output->test($key_cache)) {
            //$this->view->popular_users = Model_Listing::distinct('us')->sort(array('nv' => -1))->limit(100);
            $tmp   = Model_Listing::distinct('us');
            shuffle($tmp);
            $users = array();
            //foreach($tmp->skip(rand(0,100)) as $item) {
            foreach($tmp as $item) {
                $user = Model_User::find($item);
                if(!empty($user->cid)){
            //        if(empty($user->company->image)) {continue;}
                }else{
            //        if(empty($user->pp)) {continue;}
                }
                $users[] = $user;
                if(count($users) > 15) {break;}
            }
            $this->view->intro_users = $users; 
            $this->view->tot_user    = Model_User::all(array('sa' => Model_User::STATUS_ACTIVE))->count();
		    $this->view->tot_listing = Model_Listing::all(array('sa' => Model_Listing::STATUS_PUBLISHED))->count();
        }

        $key_cache1 = $this->view->key_homepage_new_user1 = 'homepage_new_users1';
        $key_cache2 = $this->view->key_homepage_new_user2 = 'homepage_new_users2';
        
        if (!$cache_output->test($key_cache1) || !$cache_output->test($key_cache2)) {
            $tmp = Model_User::all(array('sa' => Model_User::STATUS_ACTIVE, 'pp' => array('$exists' => true)))->sort(array('c_dt' => -1));
            if ($tmp->count() == 0) {
                $tmp = Model_User::all(array('sa' => Model_User::STATUS_ACTIVE))->sort(array('c_dt' => -1));
            }
            $this->view->new_users = $tmp;
        }
        $key_cache = $this->view->key_homepage_new_listing = 'homepage_new_listing';
        if (!$cache_output->test($key_cache)) {
            $this->view->user_list = Model_User::all(array('sa' => Model_User::STATUS_ACTIVE))->limit(100)->sort(array('nv' => -1));
            $this->view->new_listing = Model_Listing::all(array('sa' => Model_Listing::STATUS_PUBLISHED, 'phc' => array('$gte' => 1)))->sort(array('c_dt' => -1))->limit(3);
        }

        //key_homepage_popular_listings
        $key_cache = $this->view->key_homepage_popular_listings = 'homepage_popular_listings';
        if (!$cache_output->test($key_cache)) {
            $this->view->pop_listing = Model_Listing::all(array('sa' => Model_Listing::STATUS_PUBLISHED, 'phc' => array('$gte' => 1)))->sort(array('nv' => -1))->limit(3);
        }

        //WILL BE USING PETS UNTIL ENOUGH CONTENT
        $key_cache = $this->view->key_homepage_category_property = 'homepage_category_pets';
        if (!$cache_output->test($key_cache)) {
            //$cat = Model_Category::one(array('id' => 'mc49'));//property
            $cat = Model_Category::find(PET_CATEGORY);//pets
            if (!empty($cat)) {
		        $this->view->pro_listing = $cat->getMostRecentListing(4);
        		$this->view->pro_users = $cat->getDistinctUser(8);
            }
        }

        //WILL BE USING CLOTHING UNTIL ENOUGH CONTENT
        $key_cache = $this->view->key_homepage_category_car = 'homepage_category_fashion';
        if (!$cache_output->test($key_cache)) {
            //$cat = Model_Category::one(array('id' => 'mc55'));//car
            $cat = Model_Category::find(FASHION_CATEGORY);//fashion
            if (!empty($cat)) {
                $this->view->car_listing = $cat->getMostRecentListing(4);
                $this->view->car_users = $cat->getDistinctUser(8);
            }
        }

        //WILL BE USING ELECTRONICS UNTIL ENOUGH CONTENT
        $key_cache = $this->view->key_homepage_category_job = 'homepage_category_electronics';
        if (!$cache_output->test($key_cache)) {        
            //$cat = Model_Category::one(array('id' => 'mc59'));//job
            $cat = Model_Category::find(ELECTRONIC_CATEGORY);//fashion
            if (!empty($cat)) {
                $this->view->job_listing = $cat->getMostRecentListing(5);
                $this->view->job_users = $cat->getDistinctUser(8);
            }
        }

        //WILL BE USING HEALTH AND BEAUTY UNTIL ENOUGH CONTENT
        $key_cache = $this->view->key_homepage_category_bus = 'homepage_category_health';
        if (!$cache_output->test($key_cache)) {        
            //$cat = Model_Category::one(array('id' => 'mc52'));//business
            $cat = Model_Category::find(HEALTH_CATEGORY);//fashion
            if (!empty($cat)) {
                $this->view->bus_listing = $cat->getMostRecentListing(5);
                //$this->view->bus_users = Model_Company::all(array('st' => Model_Company::STATUS_ACTIVE, 'un' => array('$exists' => true), 'im' => array('$exists' => true)))->sort(array('c_dt' => -1))->limit(8);
                $this->view->bus_users = $cat->getDistinctUser(8);
            }	
        }

		//load bookmark
        $list = Model_Bookmark::getList();
        $bookmark = array();
        if (!empty($list)) {
            foreach ($list as $bmk) {
                if (!empty($bmk->listing)) {
                    $bookmark[] = (string) $bmk->listing->_id;
                }
            }
        }
        $this->view->bookmark = $bookmark;
        //$this->_forward('index', 'index', 'homepage');
    }

    public function aboutUsAction()
    {
        $this->addTitle('关于猫找网');
        $this->render('mkt-about-us');
    }

    public function advertisingAction()
    {
        $this->addTitle('广告投放与品牌推广');
        $this->render('mkt-advertising');
    }

    public function postAnAdAction()
    {
        $this->render('mkt-post-an-ad');
    }

    public function bulkListingAction()
    {
        $this->addTitle('免费商家营销服务');
		if ($this->_request->isPost()){
			 $subject = '申请开通猫找网商家营销服务';
			 $message = '';
			Ac_Util::sendEmail($subject, $message, 'marketing@maozhao.com', true, array('name' => $_POST['fname'], 'tel' => $_POST['tel'], 'email' => $_POST['email'], 'url' => $_POST['url']), Ac_Mail::TEMPLATE_CAMPAIGN_BULKLISTING);
			$session = new Zend_Session_Namespace('bulklisting');
			$session->email = $_POST['email'];
			$this->_redirect('/default/index/bulk-listing-success');	
		}
        $this->render('mkt-bulk-listing');
    }
	
	public function bulkListingSuccessAction()
    {	
        $this->addTitle('免费商家营销服务');
		$session = new Zend_Session_Namespace('bulklisting');
		$this->view->email = $session->email;
		unset($session->email);
        $this->render('mkt-bulk-listing-success');
    }
	
    public function companyAccountAction()
    {
        $this->render('mkt-company-account');
    }

    public function newsletterAction()
    {
        $this->addTitle('与猫找网互动');
        $this->render('mkt-newsletter');
    }

    public function contactUsAction()
    {
        $this->addTitle('联系猫找网');
        $this->render('mkt-contact');
    }
    

    public function privacyAction()
    {
        $this->addTitle('隐私权声明');
        $this->render('mkt-privacy');
    }

    public function prohibitAction()
    {
        $this->render('mkt-prohibit');
    }

    public function termOfUseAction()
    {
        $this->addTitle('使用条款和规则');
        $this->render('mkt-term-of-use');
    }
	
	public function findCompanyAction()
    {
		$num = Model_Company::one(array('company_name' => $_POST['data']));

		if (empty($num)) {
			$res = 'ok';
		} else {
			$res = 'not';
		}
		$this->_helper->json(array('res' => $res));
	}
	
	public function searchCompanyAction()
    {
		if ($_POST['data']!=$this->loggedin_user->company->company_name){
			$num = Model_Company::one(array('company_name' => $_POST['data']));
		} else {
			$num = 'not ok';
		}
		
		if (empty($num)) {
			$res = 'ok';
		} else {
			$res = 'not';
		}
		$this->_helper->json(array('res' => $res));
	}

	
    public function bookmarkAction()
    {
        if ($this->_request->isPost() && $this->_request->isXmlHttpRequest()) {
            if(Model_Bookmark::addListing($_POST['data'])) {
                $res = '1';
                $this->_helper->json(array('result' => $res, 'value'=>$this->view->t('Saved')));
            }
        }
        exit;
    }
    
    public function bookmarkRemoveAction()
    {
        if ($this->_request->isPost() && $this->_request->isXmlHttpRequest()) {
        	$uniqid = $_COOKIE['ac_bookmark'];
            Model_Bookmark::remove(array('ls' => $_POST['data'], 'uid' => $uniqid));
            $res = '1';
            $this->_helper->json(array('result' => $res, 'value'=>$this->view->t('Save')));
        
        }
        exit;
    }
	
	public function bookmarkCompanyAction()
    {
        if ($this->_request->isPost() && $this->_request->isXmlHttpRequest()) {
            if(Model_Bookmark::storeCompany($_POST['data'])) {
                $res = 'ok';
                $this->_helper->json(array('res' => $res, 'value'=>$this->view->t('Saved')));
            }
        }
        exit;
    }
    
    public function shorturlAction()
    {
        $res = Ac_Util::redirect($this->_request->getParam('shorturl'));
        var_dump($res);exit;
        //if it doesn't work let's go back to the homepage
        $this->_redirect('/');
    }
    
    public function mobileAction() 
    {
        if ($_SERVER['HTTP_HOST'] == 'm.hongkong.asiaclassified.com') {
            $this->_redirect('/');
        }
       //redirect if lang not set.
        if (!in_array('lang', array_keys($this->_request->getParams()))) {
            $arr = array_keys((array) Zend_Locale::getBrowser());
            if (substr($arr[0], 0, 2) == 'zh') {
                $lang = 'tc';
            } else {
                $lang = 'en';
            }
            $this->_redirect('/default/index/mobile/lang/'.$lang);
        }
        
        if ($this->current_language == 'tc') {
             //$session = new Zend_Session_Namespace('current_language');
             //unset($session->current_language);
            //$script = 'index-zh';
            $script = 'mkt-mobile-zh';
        } else {
            //$script = 'index-en';
            $script = 'mkt-mobile-en';
        }        
        $this->_helper->layout->disableLayout();
        $this->render($script);
    }
    
    public function trackAction() 
    {
        var_dump($_GET);
        $type = $_GET['t'];
        $url_id  = $_GET['u'];
        $short_url = Model_ShortUrl::one(array('_id' => $url_id));
        //var_dump($short_url->longurl);exit;
        
        //let track the url
        Model_Link::track($short_url->lu);
        header('HTTP/1.1 302 Moved Temporarly');
        header('Location: ' . $short_url->lu);
        exit;        
    }

}



